package com.ssy.lingxi.marketing.serviceimpl.base.coupon;

import cn.hutool.core.date.DateUtil;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.marketing.entity.coupon.MerchantCouponDO;
import com.ssy.lingxi.marketing.entity.coupon.MerchantCouponHistoryDO;
import com.ssy.lingxi.marketing.entity.coupon.PlatformCouponDO;
import com.ssy.lingxi.marketing.entity.coupon.PlatformCouponHistoryDO;
import com.ssy.lingxi.marketing.model.dto.ActivityInnerRecordRespDTO;
import com.ssy.lingxi.marketing.model.dto.ActivityRecordPageReqDTO;
import com.ssy.lingxi.marketing.model.vo.coupon.response.MerchantCouponHistoryResponse;
import com.ssy.lingxi.marketing.model.vo.coupon.response.PlatformCouponHistoryResponse;
import com.ssy.lingxi.marketing.repository.MerchantCouponHistoryRepository;
import com.ssy.lingxi.marketing.repository.PlatformCouponHistoryRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 基础优惠券记录服务实现类
 * @author yzc
 * @version 2.0.0
 * @date 2021/8/16
 */
@Slf4j
@Service
public class BaseCouponRecordService {

    @Resource
    private MerchantCouponHistoryRepository merchantCouponHistoryRepository;
    @Resource
    private PlatformCouponHistoryRepository platformCouponHistoryRepository;

    /**
     * 查询商家优惠券流转记录
     * @param merchantCouponDO 商家优惠券
     * @return 返回结果
     */
    public List<MerchantCouponHistoryResponse> listMerchantCouponRecord(MerchantCouponDO merchantCouponDO) {
        List<MerchantCouponHistoryDO> historyList = merchantCouponHistoryRepository.findAllByCouponId(merchantCouponDO.getId(), Sort.by("id"));
        List<MerchantCouponHistoryResponse> historyResponseList = historyList.stream().map(historyDO -> {
            MerchantCouponHistoryResponse merchantCouponHistoryResponse = new MerchantCouponHistoryResponse();
            merchantCouponHistoryResponse.setCreateTime(historyDO.getCreateTime());
            merchantCouponHistoryResponse.setOperatorId(historyDO.getOperatorId());
            merchantCouponHistoryResponse.setOperatorName(historyDO.getOperatorName());
            merchantCouponHistoryResponse.setOperatorOrgName(historyDO.getOperatorOrgName());
            merchantCouponHistoryResponse.setOperatorJobTitle(historyDO.getOperatorJobTitle());
            merchantCouponHistoryResponse.setOperation(historyDO.getOperation());
            merchantCouponHistoryResponse.setStatus(historyDO.getStatus());
            merchantCouponHistoryResponse.setStatusName(historyDO.getStatusName());
            merchantCouponHistoryResponse.setRemark(historyDO.getRemark());
            return merchantCouponHistoryResponse;
        }).collect(Collectors.toList());

        return historyResponseList;
    }

    /**
     * 保存商家优惠券流转记录
     * @param loginUser 登录用户信息
     * @param merchantCouponDO 商家优惠券
     * @param operation 操作
     * @param status 状态
     * @param statusDesc 状态描述
     */
    public void saveMerchantCouponRecord(UserLoginCacheDTO loginUser, MerchantCouponDO merchantCouponDO, String operation, Integer status, String statusDesc) {
        MerchantCouponHistoryDO merchantCouponHistoryDO = new MerchantCouponHistoryDO();
        merchantCouponHistoryDO.setCouponId(merchantCouponDO.getId());
        merchantCouponHistoryDO.setCreateTime(System.currentTimeMillis());
        merchantCouponHistoryDO.setMemberId(loginUser.getMemberId());
        merchantCouponHistoryDO.setMemberName(loginUser.getCompany());
        merchantCouponHistoryDO.setRoleId(loginUser.getMemberRoleId());
        merchantCouponHistoryDO.setRoleName(loginUser.getMemberRoleName());
        merchantCouponHistoryDO.setOperatorId(loginUser.getUserId());
        merchantCouponHistoryDO.setOperatorName(loginUser.getUserName());
        merchantCouponHistoryDO.setOperatorRoleName(loginUser.getUserRoleName());
        merchantCouponHistoryDO.setOperatorOrgName(loginUser.getUserOrgName());
        merchantCouponHistoryDO.setOperatorJobTitle(loginUser.getUserJobTitle());
        merchantCouponHistoryDO.setOperation(operation);
        merchantCouponHistoryDO.setStatus(status);
        merchantCouponHistoryDO.setStatusName(statusDesc);
        merchantCouponHistoryRepository.saveAndFlush(merchantCouponHistoryDO);
    }

    /**
     * 查询平台优惠券流转记录
     * @param platformCouponDO 商家优惠券
     * @return 返回结果
     */
    public List<PlatformCouponHistoryResponse> listPlatformCouponRecord(PlatformCouponDO platformCouponDO) {
        List<PlatformCouponHistoryDO> historyList = platformCouponHistoryRepository.findAllByCouponId(platformCouponDO.getId(), Sort.by("id"));
        List<PlatformCouponHistoryResponse> historyResponseList = historyList.stream().map(historyDO -> {
            PlatformCouponHistoryResponse platformCouponHistoryResponse = new PlatformCouponHistoryResponse();
            platformCouponHistoryResponse.setCreateTime(historyDO.getCreateTime());
            platformCouponHistoryResponse.setOperatorId(historyDO.getOperatorId());
            platformCouponHistoryResponse.setOperatorName(historyDO.getOperatorName());
            platformCouponHistoryResponse.setOperatorOrgName(historyDO.getOperatorOrgName());
            platformCouponHistoryResponse.setOperatorJobTitle(historyDO.getOperatorJobTitle());
            platformCouponHistoryResponse.setOperation(historyDO.getOperation());
            platformCouponHistoryResponse.setStatus(historyDO.getStatus());
            platformCouponHistoryResponse.setStatusName(historyDO.getStatusName());
            platformCouponHistoryResponse.setRemark(historyDO.getRemark());
            return platformCouponHistoryResponse;
        }).collect(Collectors.toList());

        return historyResponseList;
    }

    /**
     * 保存商家优惠券流转记录
     * @param loginUser 登录用户信息
     * @param platformCouponDO 平台优惠券
     * @param operation 操作
     * @param status 状态
     * @param statusDesc 状态描述
     */
    public void savePlatformCouponRecord(UserLoginCacheDTO loginUser, PlatformCouponDO platformCouponDO, String operation, Integer status, String statusDesc) {
        PlatformCouponHistoryDO platformCouponHistoryDO = new PlatformCouponHistoryDO();
        platformCouponHistoryDO.setCouponId(platformCouponDO.getId());
        platformCouponHistoryDO.setCreateTime(System.currentTimeMillis());
        platformCouponHistoryDO.setMemberId(loginUser.getMemberId());
        platformCouponHistoryDO.setMemberName(loginUser.getCompany());
        platformCouponHistoryDO.setRoleId(loginUser.getMemberRoleId());
        platformCouponHistoryDO.setRoleName(loginUser.getMemberRoleName());
        platformCouponHistoryDO.setOperatorId(loginUser.getUserId());
        platformCouponHistoryDO.setOperatorName(loginUser.getUserName());
        platformCouponHistoryDO.setOperatorRoleName(loginUser.getUserRoleName());
        platformCouponHistoryDO.setOperatorOrgName(loginUser.getUserOrgName());
        platformCouponHistoryDO.setOperatorJobTitle(loginUser.getUserJobTitle());
        platformCouponHistoryDO.setOperation(operation);
        platformCouponHistoryDO.setStatus(status);
        platformCouponHistoryDO.setStatusName(statusDesc);
        platformCouponHistoryRepository.saveAndFlush(platformCouponHistoryDO);
    }

    public PageData<ActivityInnerRecordRespDTO> pagePlatformActivityInnerRecordCommon(UserLoginCacheDTO loginUser, ActivityRecordPageReqDTO pageVO) {
        // 组装查询条件
        Specification<PlatformCouponHistoryDO> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if(pageVO.getDataId()!=null) {
                list.add(criteriaBuilder.equal(root.get("couponId").as(Long.class), pageVO.getDataId()));
            }
            if(loginUser!=null) {
                list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
                list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            }
            if(pageVO.getStartTime()!=null){
                list.add(criteriaBuilder.ge(root.get("operateTime").as(Long.class), pageVO.getStartTime()));
            }
            if(pageVO.getEndTime()!=null){
                list.add(criteriaBuilder.le(root.get("operateTime").as(Long.class), pageVO.getEndTime()));
            }
            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        // 组装分页参数
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by(pageVO.getSort()? Sort.Direction.ASC:Sort.Direction.DESC,"createTime"));

        Page<PlatformCouponHistoryDO> recordList = platformCouponHistoryRepository.findAll(spec, page);
        List<ActivityInnerRecordRespDTO> resultList = recordList.stream().map(r -> {
            ActivityInnerRecordRespDTO entity = new ActivityInnerRecordRespDTO();
            entity.setOperator(r.getOperatorName());
            entity.setDepartment(r.getOperatorOrgName());
            entity.setJobTitle(r.getOperatorJobTitle());
            entity.setStatus(r.getStatus());
            entity.setStatusName(r.getStatusName());
            entity.setOperate(r.getOperation());
            entity.setOperateTime(DateUtil.format(DateUtil.date(r.getCreateTime()), "yyyy-MM-dd HH:mm"));
            entity.setOpinion(r.getRemark());
            entity.setDataId(r.getCouponId());
            return entity;
        }).collect(Collectors.toList());
        return new PageData<>(recordList.getTotalElements(), resultList);
    }


    public PageData<ActivityInnerRecordRespDTO> pageMerchantActivityInnerRecordCommon(UserLoginCacheDTO loginUser, ActivityRecordPageReqDTO pageVO) {
        // 组装查询条件
        Specification<MerchantCouponHistoryDO> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if(pageVO.getDataId()!=null) {
                list.add(criteriaBuilder.equal(root.get("couponId").as(Long.class), pageVO.getDataId()));
            }
            if(loginUser!=null) {
                list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
                list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            }
            if(pageVO.getStartTime()!=null){
                list.add(criteriaBuilder.ge(root.get("createTime").as(Long.class), pageVO.getStartTime()));
            }
            if(pageVO.getEndTime()!=null){
                list.add(criteriaBuilder.le(root.get("createTime").as(Long.class), pageVO.getEndTime()));
            }
            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        // 组装分页参数
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by(pageVO.getSort()? Sort.Direction.ASC:Sort.Direction.DESC,"createTime"));

        Page<MerchantCouponHistoryDO> recordList = merchantCouponHistoryRepository.findAll(spec, page);
        List<ActivityInnerRecordRespDTO> resultList = recordList.stream().map(r -> {
            ActivityInnerRecordRespDTO entity = new ActivityInnerRecordRespDTO();
            entity.setOperator(r.getOperatorName());
            entity.setDepartment(r.getOperatorOrgName());
            entity.setJobTitle(r.getOperatorJobTitle());
            entity.setStatus(r.getStatus());
            entity.setStatusName(r.getStatusName());
            entity.setOperate(r.getOperation());
            entity.setOperateTime(DateUtil.format(DateUtil.date(r.getCreateTime()), "yyyy-MM-dd HH:mm"));
            entity.setOpinion(r.getRemark());
            entity.setDataId(r.getCouponId());
            return entity;
        }).collect(Collectors.toList());
        return new PageData<>(recordList.getTotalElements(), resultList);
    }

}